<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket Chat</title>
</head>

<body>
  <div id="loginSection">
    <input type="text" id="usernameInput" placeholder="输入用户名">
    <button onclick="login()">登录</button>
  </div>
  <div id="chatSection" style="display: none;">
    <p>你的用户ID：<span id="userIdDisplay"></span></p>
    <input type="text" id="toUserIdInput" placeholder="输入对方用户ID">
    <input type="text" id="messageInput" placeholder="Type your message">
    <button onclick="sendMessage()">Send</button>
    <div id="chatWindow"></div>
  </div>

  <script>
    const socket = new WebSocket('ws://localhost:8080');
    let userId;
    let username;

    socket.addEventListener('open', (event) => {
      console.log('Connected to server');
    });

    socket.addEventListener('message', (event) => {
      const data = JSON.parse(event.data);
      if (data.type === 'loginSuccess') {
        userId = data.userId;
        username = data.username;
        document.getElementById('loginSection').style.display = 'none';
        document.getElementById('chatSection').style.display = 'block';
        // 在页面上显示userId
        document.getElementById('userIdDisplay').textContent = userId;
      } else if (data.type ==='message') {
        const chatWindow = document.getElementById('chatWindow');
        const messageDiv = document.createElement('div');
        messageDiv.textContent = `${data.fromUsername}: ${data.content}`;
        chatWindow.appendChild(messageDiv);
      } else if (data.type === 'error') {
        alert(data.message);
      }
    });

    socket.addEventListener('close', (event) => {
      console.log('Connection closed');
    });

    function login() {
      const usernameInput = document.getElementById('usernameInput');
      const username = usernameInput.value;
      if (username) {
        const loginData = {
          type: 'login',
          username: username
        };
        socket.send(JSON.stringify(loginData));
      }
    }

    function sendMessage() {
      const toUserIdInput = document.getElementById('toUserIdInput');
      const toUserId = toUserIdInput.value;
      const messageInput = document.getElementById('messageInput');
      const content = messageInput.value;
      if (toUserId && content) {
        const messageData = {
          type:'message',
          toUserId: toUserId,
          content: content
        };
        socket.send(JSON.stringify(messageData));
        messageInput.value = '';
        toUserIdInput.value = '';
      }
    }
  </script>
</body>

</html>